package com.cdvtc.forum_system.web.servlet;

import com.cdvtc.forum_system.model.User;
import com.cdvtc.forum_system.service.UserService;
import com.cdvtc.forum_system.service.Impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class Forum_systemServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理GET请求（例如显示登录页面）
        req.getRequestDispatcher("forum_login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");

        // 获取表单参数
        String userAccount = req.getParameter("username");
        String userPassword = req.getParameter("password");

        // 调用Service层进行登录验证
        User user = userService.login(userAccount, userPassword);

            System.out.println(user);
        if (user != null) {
            // 登录成功
            HttpSession session = req.getSession();
            session.setAttribute("currentUser", user); // 将用户信息存入Session
            System.out.println("userLogin");

            // 跳转到论坛首页（带用户昵称的界面）
            resp.sendRedirect(req.getContextPath() + "/forum_system.jsp");
        } else {
            System.out.println("useError");

            // 登录失败
            req.setAttribute("errorMsg", "账号或密码错误");
            req.getRequestDispatcher("forum_login.jsp").forward(req, resp);
        }
    }
}
